package com.hdu.clj.fitness

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login.*
import java.io.*

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        ActivityCollector.addActivity(this)

        val startIcon = Typeface.createFromAsset(assets,"iconfont.ttf")
        userIcon.setTypeface(startIcon)
        userIcon.setText(R.string.user)
        toReg.setTypeface(startIcon)
        toReg.setText(R.string.reg)
        startSport.setTypeface(startIcon)
        startSport.setText(R.string.log)


        //打开用户数据库
        val dbHelper = userDatabase(this,"Users.db",1)
        val db = dbHelper.writableDatabase

        if (load("remAcc").isNotEmpty()&&load("remPass").isNotEmpty()&&load("isRem").isNotEmpty()&&load("isRem").equals("true")){
            val remUser = load("remAcc")
            val remPass = load("remPass")
            nameLog.setText(remUser)
            passLog.setText(remPass)
            rememberMe.isChecked = true
//            Log.d("curdata",remUser)
            //save("false","isRem")
        }
        val userAcc = nameLog.text
        val userPass = passLog.text
        var ver = 1
        //点击开始运动按钮
        startSport.setOnClickListener {
            //获取数据表的版本号
            if (load("ver").isNotEmpty()){
                ver = load("ver").toInt()
            }
            //检查用户名或密码输入是否为空
            if (userAcc.isNotEmpty()&&userPass.isNotEmpty()) {
                //查找用户是否已经注册
                val sname = db.rawQuery("select * from Users where acc = ?", arrayOf(userAcc.toString()))
                if (sname.moveToFirst()) {
                    //检查密码是否正确
                    val spass = sname.getString(sname.getColumnIndex("pass"))
                    val userName = sname.getString(sname.getColumnIndex("name"))
                    if (userPass.toString().equals(spass)){
                        Log.d("curdata","login $userAcc ver $ver")
                        //密码正确
                        //根据用户名，创建每个用户的日常统计数据表，表明为用户名+database，存储该用户的数据
//                        val dbDayNum = DayNumDatabase(this,"Fit.db",ver,"abc"+userAcc.toString())
//                        dbDayNum.writableDatabase
                        //记住用户名和密码
                        if (rememberMe.isChecked){
                            save(userAcc.toString(),"remAcc")
                            save(userPass.toString(),"remPass")
                            save("true","isRem")
                            rememberMe.isChecked = true
                        }
                        else{
                            save("false","isRem")
                        }
                        //将用户名存放，便于后续数据读取
                        save(userAcc.toString(),"userAcc")
                        save(userName.toString(),"userName")

                        val intent = Intent(this,MainActivity::class.java)
                        startActivity(intent)
                    }
                    else{
                        passLog.text.clear()
                        Toast.makeText(this, "密码错误，请重新输入!", Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    nameLog.text.clear()
                    passLog.text.clear()
                    Toast.makeText(this, "用户未注册!", Toast.LENGTH_SHORT).show()
                }
            }
            else{
                Toast.makeText(this, "请输入完整的用户信息!", Toast.LENGTH_SHORT).show()
            }

        }
        //注册页面
        toReg.setOnClickListener {
            val intent = Intent(this,RegActivity::class.java)
            startActivity(intent)
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }
    private fun save(inputText: String,data:String) {
        try {
            val output = openFileOutput(data, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText)
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    private fun load(data:String): String {
        val content = StringBuilder()

        try {
            val input = openFileInput(data)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch (e:IOException){
            e.printStackTrace()
        }
        return content.toString()
    }
}
